<script setup lang='ts' name="add-menu">
import type { PlusColumn } from 'plus-pro-components'

import { departmentAddOrEdit, departmentList } from '@fl/api/iam-api'
import { SubmitBtn } from '@fl/components'
import { ElDialog } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { ref, toRefs, watch } from 'vue'

import { useTable as useTable2 } from '../../hooks/use-table'

const props = withDefaults(defineProps<{
    data?: any
    deptId?: string
    modelValue: boolean
}>(), {
    data: () => { },
})

const emits = defineEmits(['update:modelValue', 'confirm'])
const show = defineModel<boolean>('show', { required: true })
const { data, deptId, modelValue } = toRefs(props)
const { arrayToTree } = useTable2()

const initialState = {
    deptId: '',
    deptName: '',
    email: '',
    leader: '',
    orderNum: 0,
    parentId: '',
    phone: '',
    status: 0,
}
const form = ref(cloneDeep(initialState))
const formRef = ref()

const equityOptions = ref<any>([])
const equityOptionsOrigin = ref<any>([])

async function submit() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        console.log('form.value', form.value)
        const obj = {
            deptName: form.value.deptName,
            email: form.value.email,
            enterprise: deptId.value,
            leader: form.value.leader,
            orderNum: form.value.orderNum,
            parentId: Number(form.value.parentId),
            phone: form.value.phone,
            status: String(form.value.status),
        }
        departmentAddOrEdit({ ...obj }, Number(form.value?.deptId)).then((res: any) => {
            if (res.code === 200) {
                close()
                ElMessage.success('保存成功')
                emits('confirm')
            }
            else { ElMessage({ message: res.msg, type: 'error' }) }
        })
    }
}

function close() {
    show.value = false
    formRef.value.formInstance.resetFields()
    emits('update:modelValue', false)
}

// 组织机构树
function getTreeData() {
    departmentList({ enterprise: deptId.value }).then((res) => {
        equityOptionsOrigin.value = cloneDeep(res?.data)
        equityOptions.value = arrayToTree(res?.data, 'parentId', 'deptId')
        console.log('部门机构树', equityOptions.value)
        if (equityOptionsOrigin.value.length === 0) {
            rules.parentId = [
                { message: '', required: false },
            ]
        }
    })
}

// 选择上级部门
function parentIdChange(value) {
    const target = equityOptionsOrigin.value.find((v: any) => v.deptId === value[value.length - 1])
    // console.log('parentIdChange', value, target)
    form.value.parentId = target.deptId
}

watch(data, (val: any) => {
    // console.log('部门详情', val)
    if (val.value) {
        form.value = {
            ...val.value,
            status: Number(val.value.status),
        }
    }
    else {
        form.value = {
            ...initialState,
        }
    }
}, {
    deep: true,
})

watch(modelValue, (val: any) => {
    if (val) {
        getTreeData() // 刷新机构树
    }
})

const columns: PlusColumn[] = [
    {
        label: '上级部门',
        prop: 'parentId',
    },
    {
        label: '部门名称',
        prop: 'deptName',
    },
    {
        fieldProps: { min: 0, precision: 0 },
        label: '排序',
        prop: 'orderNum',
        valueType: 'input-number',
    },
    {
        label: '负责人',
        prop: 'leader',
    },
    {
        label: '联系电话',
        prop: 'phone',
    },
    {
        label: '邮箱',
        prop: 'email',
    },
    {
        label: '部门状态',
        prop: 'status',
    },

]

const rules = {
    deptName: [
        {
            message: '请输入部门名称',
            required: true,
        },
    ],
    parentId: [
        {
            message: '请选择上级',
            required: true,
        },
    ],
}
</script>

<template>
    <ElDialog v-model="modelValue"
              width="600"
              :title="form?.deptId ? '编辑' : '新增'"
              @close="close"
    >
        <div class="mt-20">
            <PlusForm ref="formRef"
                      v-model="form"
                      :columns="columns"
                      :label-width="120"
                      :rules="rules"
                      :has-footer="false"
                      :row-props="{ gutter: 20 }"
            >
                <template #plus-field-parentId>
                    <el-cascader v-model="form.parentId"
                                 :options="equityOptions"
                                 :props="{ label: 'deptName', value: 'deptId', checkStrictly: true }"
                                 :show-all-levels="false"
                                 @change="parentIdChange($event)"
                    />
                </template>

                <template #plus-field-status>
                    <el-radio-group v-model="form.status">
                        <el-radio label="正常"
                                  :value="0"
                        />

                        <el-radio label="停用"
                                  :value="1"
                        />
                    </el-radio-group>
                </template>
            </plusform>
        </div>

        <div class="mx-auto mt20 flex justify-center">
            <el-button @click="close">
                取消
            </el-button>

            <SubmitBtn type="primary"
                       @click="submit"
            >
                提交
            </SubmitBtn>
        </div>
    </ElDialog>
</template>

<style lang="less" scoped>
.info-title {
    font-size: 16px;
    font-weight: 600;
    line-height: 50px;
}
</style>
